package com.liao.liaowenlong;

import android.app.Service;
import android.content.Intent;
import android.os.IBinder;
import android.widget.Toast;

import java.io.Serializable;
import java.util.ArrayList;

public class MyService extends Service {
    public MyService() {
    }

    @Override
    public IBinder onBind(Intent intent) {
        return null;
    }

    @Override
    public int onStartCommand(Intent intent, int flags, int startId) {
        BookDB bookDB = new BookDB(this);
        String type = intent.getStringExtra("type");
        String bookName = intent.getStringExtra("bookName");
        BookInfo bookInfo = (BookInfo) intent.getSerializableExtra("bookInfo");
        Intent intent1 = new Intent(FragmentMain1LayoutFragment.MyReceiver.ACTION);
        if ("query".equals(type)) {
            ArrayList<BookInfo> bookInfos = bookDB.queryAllBook(bookDB.getReadableDatabase());
            intent1.putExtra("books", bookInfos);
        } else if ("insert".equals(type) && bookInfo != null) {
            long l = bookDB.insertBook(bookDB.getWritableDatabase(), bookInfo);
            Toast.makeText(this, "" + l, Toast.LENGTH_SHORT).show();
            intent1.putExtra("number", l);
        } else if ("delete".equals(type) && bookName != null) {
            long l = bookDB.deleteBook(bookDB.getWritableDatabase(), bookName);
            intent1.putExtra("number", l);
        }
        intent1.putExtra("type", type);
        sendBroadcast(intent1);
        return super.onStartCommand(intent, flags, startId);
    }
}
